package com.shop.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shop.common.constant.RedisConstant;
import com.shop.common.util.CodeUtils;
import com.shop.common.util.StrUtils;
import com.shop.server.feign.SmsFeign;
import com.shop.server.service.CodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author ghy
 * @version 1.0
 * @date 2020-10-30
 */
@Service
public class CodeServiceImpl implements CodeService {


    @Autowired
    SmsFeign smsFeign;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 发送验证码
     *
     * @param phone
     * @return
     */
    @Override
    public Boolean sendCode(String phone) {
        //1.生成验证码
        String validateCode = CodeUtils.getCheckCode4();

        //2.存储到redis
        //  shop_register_13711112222 : 5236
        //  shop_login_13711112222 : 5266
        //  shop_login_token : slkdfuonsdlgoasdu
        String codeKey = StrUtils.getRedisKey(RedisConstant.SHOP_REGISTER, phone);
        //redisTemplate.opsForValue().set(codeKey, validateCode, 5,TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(codeKey, validateCode);

        //3.发送到手机
        //调用发送短信的接口
        String result = smsFeign.send(phone, validateCode);

        Map map = JSON.parseObject(result, Map.class);

        String message = (String) map.get("Message");
        String code = (String) map.get("Code");

        if("OK".equalsIgnoreCase(message) && "OK".equalsIgnoreCase(code)) {
            return true;
        }
        return false;

    }
}
